from flask import Flask, request, jsonify
import pymysql
from flask_cors import CORS
import requests
from db import MySQLConnection
import json
import datetime

app = Flask(__name__)
CORS




#@app.route('/api/hello')
#def hello():
#    db = Database()
#    db.connect()
#    result = db.execute_query("SELECT * FROM user")
#
#    rows = []
#    for row in result:
#        rows.append(row)
#        print(jsonify(row))
#
#    db.close_connection()
#
#    return rows, 200


#@app.route('/api/greet', methods=['POST', 'GET'])
#def greet():
#    print("----------->", request.json['name'])
#    print("----------->", request.json['syncSingleImage'])
#    print("----------->", request.json['serviceType0'])
#    print("----------->", request.json['method'])
#    print("----------->", request.json['method'])
#
#    url = "http://192.168.162.110:5555/"
#    payload = {
#        "method": "queryTeamUserPage"
#    }
#    headers = {
#        'content-type': 'application/json',
#        'token': '5491350e-17aa-4305-80af-3e39c4e16edb',
#        'X-Request-Type': 'console'
#    }
#
#    response = requests.post(url, json=payload, headers=headers)
#    data = response.json()
#    return data


#@app.route('/api/welcome')
#def welcome():
#    return 'Welcome to the Flask API!'


# 注册接口
@app.route('/api/register', methods=['POST'])
def register_user():
    db = MySQLConnection()
    try:
        db.connect()

        account = request.json.get('account')
        name = request.json.get('name')
        pwd = request.json.get('pwd')
        email = request.json.get('email')
        if not name:
            return jsonify({'message': '名称不能为空', 'code': -1}), 400
        if not account:
            return jsonify({'message': '账号不能为空', 'code': -1}), 400
        if not pwd:
            return jsonify({'message': '密码不能为空', 'code': -1}), 400
        # 检查account是否已存在
        query = "SELECT * FROM user WHERE account = %s"
        result = db.execute_query(query, (account,))
        print("---------", result)
        if result:
            user_data = {
                'id': result[0][0],
                'name': result[0][2],
                'account': result[0][1]
            }
            return jsonify({'message': 'Account already exists', 'code': -1, 'data': (user_data)}), 400
        else:
            # 注册新用户
            current_time = datetime.datetime.now()
            query = "INSERT INTO user (account, name,pwd, email,create_time) VALUES (%s, %s,%s, %s, %s)"
            user = db.execute_query(
                query, (account, name, pwd, email, current_time))
            db.commit()
            return jsonify({'message': 'User registered successfully', 'code': 200, 'data': user}), 200
    except pymysql.MySQLError as e:
        return jsonify({'error': str(e), 'code': -1}), 500
    finally:
        db.close()

# 登录接口
@app.route('/api/login', methods=['POST'])
def user_login():
    db = MySQLConnection()
    try:
        db.connect()
        account = request.json.get('account')
        pwd = request.json.get('pwd')
        if not account:
            return jsonify({'message': '密码不能为空！', 'code': -1}), 400
        if not account:
            return jsonify({'message': '账号不能为空！', 'code': -1}), 400
        # 检查account、pwd是否一致
        query = "SELECT * FROM user WHERE account = %s AND pwd = %s"
        result = db.execute_query(query, (account, pwd))
        print("---------", result)
        if result:
            user_data = {
                'id': result[0][0],
                'pwd': result[0][3],
                'account': result[0][1]
            }
            update = "update user set login_time=%s where id=%s"
            current_time = datetime.datetime.now()
            result = db.execute_query(update, (current_time, user_data['id']))
            db.commit()
            return jsonify({'message': '登录成功！', 'code': 200, 'data': (user_data)}), 200
        else:
            return jsonify({'message': '用户账号不存在或密码错误!', 'code': -1}), 400
    except pymysql.MySQLError as e:
        return jsonify({'error': str(e), 'code': -1}), 400
    finally:
        db.close()

# 创建job
@app.route('/api/create_job', methods=['POST'])
def create_job():
    name = request.json.get('name')
    desc = request.json.get('_describe')
    status = request.json.get('status')
    #user_id = request.json.get('user_id')
    end_time = request.json.get('end_time')
    db = MySQLConnection()
    if not all([name, desc, status]):
        return jsonify({'message': 'Missing required fields', 'code': -1}), 400

    try:
        db.connect()
        query = "INSERT INTO job (name, _describe, status, end_time,create_time) VALUES (%s, %s, %s, %s, %s)"
        current_time = datetime.datetime.now()
        end_time=convert_datetime(end_time);
        result = db.execute_query(
            query, (name, desc, status, end_time, current_time))
        db.commit()
        db.close()
        return jsonify({'message': 'Job created successfully', 'code': 200}), 200
    except pymysql.MySQLError as e:
        return jsonify({'error': str(e), 'code': -1}), 500

def convert_datetime(datetime_str):
    if "T" in datetime_str:
        dt_obj = datetime.datetime.strptime(datetime_str, "%Y-%m-%dT%H:%M:%S.%fZ")  # 解析包含 "T" 的日期时间字符串
        return dt_obj.strftime("%Y-%m-%d %H:%M:%S")  # 将日期时间格式化为 "yyyy-mm-dd" 格式
    else:
        return datetime_str


# 删除job
@app.route('/api/delete_job', methods=['POST'])
def delete_job():
    id = request.json.get('id')
    if not id:
        return jsonify({'message': 'job id不能为空！', 'code': -1}), 400
    db = MySQLConnection()
    try:
        db.connect()
        query = "delete from job where id= %s"
        result = db.execute_query(query, (id))
        db.commit()
        db.close()
        return jsonify({'message': 'Job delete successfully', 'code': 200}), 200
    except pymysql.MySQLError as e:
        return jsonify({'error': str(e), 'code': -1}), 500

# 查询job列表
@app.route('/api/query_job_list', methods=['POST'])
def query_job_list():
    db = MySQLConnection()
    try:
        db.connect()
        query = "select * from job"
        result = db.execute_query(query)

        job_list = []
        for row in result:
            job = {
                'id': row[0],
                'name': row[1],
                '_describe': row[2],
                'status': row[3],
                'create_time': row[4].strftime('%Y-%m-%d %H:%M:%S'),
                'end_time': row[5].strftime('%Y-%m-%d %H:%M:%S') if row[5] else None,
                'user_id': row[6]
            }
            job_list.append(job)
        db.commit()
        db.close()
        return jsonify({'message': 'Job delete successfully', 'code': 200, 'data': job_list}), 200
    except pymysql.MySQLError as e:
        return jsonify({'error': str(e), 'code': -1}), 500


# 更新job
@app.route('/api/update_job', methods=['POST'])
def update_job():
    db = MySQLConnection()
    try:
        db.connect()

        _describe = request.json.get('_describe')
        id = request.json.get('id')
        name = request.json.get('name')
        status = request.json.get('status')
        if not id:
            return jsonify({'message': 'id不能为空', 'code': -1}), 400
        # if not account:
        #    return jsonify({'message': '账号不能为空', 'code': -1}), 400
        # if not pwd:
        #    return jsonify({'message': '密码不能为空', 'code': -1}), 400
        # 检查数据是否存在
        query = "SELECT * FROM job WHERE id = %s"
        result = db.execute_query(query, (id,))
        if result:
            query = "update  job  set name=%s,status=%s,_describe=%s where id=%s"
            result = db.execute_query(query, (name, status, _describe, id))
            db.commit()
            db.close()
            return jsonify({'message': 'Job update successfully', 'code': 200}), 200
        else:
            return jsonify({'message': 'job id 不存在', 'code': -1}), 400
    except pymysql.MySQLError as e:
        return jsonify({'error': str(e), 'code': -1}), 500



if __name__ == '__main__':
    print("------程序启动成功-----")
    app.run(debug=True, port=8888,host="0.0.0.0")
